package com.woniuxy.intellihome.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.woniuxy.intellihome.entity.Order;
import com.woniuxy.intellihome.entity.ResponseEntity;
import com.woniuxy.intellihome.entity.ResponseState;
import com.woniuxy.intellihome.service.OrderService;
import com.woniuxy.intellihome.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author jobob
 * @since 2021-08-11
 */
@RestController
@RequestMapping("/order")
public class OrderController {

    //设置list下每页展示数量
    private int pageSize = 5;

    @Autowired
    private OrderService orderService;
    @Autowired
    private UserService userService;

    @GetMapping("/list")
    @ResponseBody
    public ResponseEntity<List<Order>> list(@RequestParam(value = "current",defaultValue = "1")Integer current,
                                            @RequestBody Order order, BindingResult result){
        //创建JSON返回语句对象
        ResponseEntity responseEntity = new ResponseEntity();

        if(current == null){
            current = 1;
        }
        //设置Order查询条件
        //订单编号、user用户、下单时间、收货人
        QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
        if (order.getOrderNum() != null && order.getOrderNum().trim().length() != 0) {
            queryWrapper.like("orderNum", order.getOrderNum());
        }
        if (order.getUserId() != 0) {
            queryWrapper.eq("userId", order.getUserId());
        }
        if (order.getOrderTime() != null && order.getOrderTime().trim().length() != 0) {
            queryWrapper.eq("orderTime", order.getOrderTime());
        }
        if (order.getAccept() != null && order.getAccept().trim().length() != 0) {
            queryWrapper.eq("accept", order.getAccept());
        }

        //检查是否存在错误
        if(result.hasFieldErrors()){
            //不存在返回无效提示
            Map<String,String> msgs = new HashMap<>();
            result.getFieldErrors().forEach(e ->{
                msgs.put(e.getField(),e.getDefaultMessage());
            });
            responseEntity.setCode(ResponseState.INVALIDARGS);
            responseEntity.setMsg("无效参数");
            responseEntity.setData(msgs);
        }else{
            //查询数据中所有科目分页信息，并返回JSON语句
            Page<Order> page = new Page<>(current,pageSize);
            //返回JSON数据
            responseEntity.setCode(ResponseState.SUCCESS);
            responseEntity.setMsg("查询成功");
            responseEntity.setData(page);
        }

        return responseEntity;
    }
}

